<template>
  <div style="margin-top: 40px">
    <!-- 查询药品库的数据 -->
    <a-row>
      <a-col :span="12">
        <a-form-item :label-col="{ span: 8 }" label="药品名称" name="drugsId">
          <a-select
            v-model:value="recordData.drugsId"
            show-search
            placeholder="请输入药品"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="drugsData"
            @search="searchDrugs"
            @change="selectDrug"
          ></a-select>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="用量" :label-col="{ span: 6 }">
          <a-input-number
            style="width: 80%"
            placeholder="数量"
            v-model:value="recordData.drugNumber"
            :min="1"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item :label-col="{ span: 8 }" label="药品用量">
          <a-input
            v-model:value="recordData.frequency"
            placeholder="请输入药品用量"
          />
        </a-form-item>
      </a-col>
      <a-col :span="6"></a-col>
      <a-col :span="6">
        <a-button @click="handlerAdd" type="primary">添加</a-button>
      </a-col>
    </a-row>
    <!-- 表格 -->
    <a-table
      tableLayout="fixed"
      :pagination="false"
      :data-source="libraryList.data"
      :columns="libraryListCloumns"
      :scroll="{ y: '42vh', scrollToFirstRowOnChange: true }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button
            @click="deleteItem(record)"
            type="primary"
            style="background-color: #f38181"
            danger
            >删除</a-button
          >
        </template>
      </template>
    </a-table>

    <a-row>
      <a-col :span="6"></a-col>
      <a-col :span="6">
        <div class="btn_box"><a-button @click="backStep">返回</a-button></div>
      </a-col>
      <a-col :span="6">
        <div class="btn_box">
          <a-button
            @click="submitDrug"
            style="margin-right: 20px; background-color: #b83b5e"
            type="primary"
            >下一步</a-button
          >
        </div>
      </a-col>
      <a-col :span="6">
        <div class="price">
          <span class="title">总价:</span>
          <span class="money">{{ totalPrice.toFixed(2) }}</span>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { apiQueryLibrary, apiLibraryDetails } from '@/api/Drugs/api'
import { libraryListCloumns } from './columns'
import { userUserStore } from '@/stores/UserStore'
import { userConsuliation } from '@/stores/ConsulitationStore'
import { message } from 'ant-design-vue'

const stepsStore = userConsuliation()
const store = userUserStore()
const userInfo: any = ref({})
const recordData = ref<any>({
  drugsId: null,
  drugNumber: null,
  frequency: '',
})
const drugsData = ref([])

//查询药品返回的数据
const drugDetails = ref<any>({})

let timeout: any = ref(null)

// 给用户添加的药品数据
const libraryList = reactive<any>({
  data: [],
})
const backStep = () => {
  stepsStore.current--
}
//删除药品
const deleteItem = (item: any) => {
  libraryList.data = libraryList.data.filter((ele: any) => {
    return item.drugsId != ele.drugsId
  })
  totalPrice.value = 0
  libraryList.data.forEach((element: any) => {
    totalPrice.value += Number(element.price) * Number(element.drugNumber)
  })
}
//添加药品
const handlerAdd = () => {
  //判断所添加的药品数量与库存的数量
  if (recordData.value.drugNumber > drugDetails.value.drugLibrary.stock) {
    return message.error('所填数量不能超过药品库库存')
  }
  let item: any = {
    ...recordData.value,
    drugsName: drugDetails.value.drugs.drugsName,
    price: drugDetails.value.drugs.price,
    stock: drugDetails.value.drugLibrary.stock,
  }
  //判读此药品是否在列表当中
  let isExist = libraryList.data.some((ele: any) => {
    return item.drugsId == ele.drugsId
  })
  if (isExist) {
    return message.error('当前药品已经在列表当中了')
  }
  //添加到列表中
  libraryList.data.push(item)
  //添加完之后清空药品信息
  recordData.value = {
    drugsId: null,
    number: null,
    frequency: '',
  }
  totalPrice.value = 0
  libraryList.data.forEach((element: any) => {
    totalPrice.value += Number(element.price) * Number(element.drugNumber)
  })
}

// 总价
const totalPrice = ref(0)

watch(
  stepsStore.getCurrent,
  () => {
    // 只要步骤为4了表示完成了然后清空本页数据
    if (stepsStore.getCurrent() == 4) {
      recordData.value = {
        drugsId: null,
        number: null,
        frequency: '',
      }
      libraryList.data = []
      console.log('第二步进入了，清空了', recordData.value)
    }
  },
  {
    deep: true,
    immediate: true,
  }
)

const submitDrug = () => {
  //药品的追加
  stepsStore.addDrugInfo(libraryList.data, totalPrice.value)
}

//获取药品列表数据
const searchDrugs = (value: any) => {
  if (timeout.value) {
    clearTimeout(timeout.value)
    timeout.value = null
  }

  timeout.value = setTimeout(async () => {
    let res = await apiQueryLibrary({
      drugsName: value,
      communityId: userInfo.value.communityId,
    })
    drugsData.value = res.data.map((ele: any) => {
      return {
        label: ele.drugsName,
        value: ele.drugsId,
        ...ele,
      }
    })
  }, 300)
}

// 选择的药品 获取药品的详细
const selectDrug = async () => {
  let res = await apiLibraryDetails({
    communityId: userInfo.value.communityId,
    drugsId: recordData.value.drugsId,
  })
  drugDetails.value = res.data
}

onMounted(() => {
  userInfo.value = store.employeeInfo
})
</script>

<style lang="less" scoped>
.btn_box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}
.price {
  display: flex;
  font-size: 28px;
  justify-content: center;
  align-items: center;
  margin-top: 8px;

  color: #d30404;

  .money {
    font-weight: 600;
  }
}
</style>
